package io.github.wslxm.springbootplus2.core.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * excel导出工具类
 * 使用示例
 * <p>
 *   @PostMapping(value = "/exportExcel")
 *   @Operation(summary = "导出excel")
 *   public void exportExcel(@ModelAttribute @Validated xxxxQuery query) {
 *         try {
 *             baseService.exportExcel(query);
 *         } catch (ErrorException e) {
 *             // 已知异常: 通过 ValidUtil.xxx 进行参数验证的异常 和 自行 throw new ErrorException() 的异常
 *             ExcelUtil.exportError(response, e);
 *         } catch (Exception e) {
 *             // 未知异常
 *             ExcelUtil.exportError(response, Result.error(ResultType.SYR_ERROR.getValue(), "导出错误", ErrorMsgUtil.getErrorStr(e)));
 *         }
 *   }
 * </p>
 *
 * @author wangsong
 * @date 2023/07/25
 */
public class XjExcelUtil {


    /**
     * 导出 xlsx
     *
     * @param excelVOS excel vos
     * @param fileName 文件名称
     * @param response 响应
     */
    public static <T> void exportXlsx(HttpServletResponse response, List<T> excelVOS, String fileName) {
        // 导出
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.write(excelVOS, true);
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出 xlsx 多 Sheet 模式
     *
     * @param excelVOSMap 导出数据集 key=Sheet 名 | list=内容
     * @param fileName 文件名称
     * @param response 响应
     */
//    public static <T> void exportXlsxMoreSheet(HttpServletResponse response, Map<String, List<T>> excelVOSMap, String fileName) {
//        // 导出
//        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
//        int index = 0;
//        for (String key : excelVOSMap.keySet()) {
//            if (index == 0) {
//                writer.renameSheet(0, key);
//                writer.write(excelVOSMap.get(key), true);
//            } else {
//                writer.setSheet(key);
//                writer.write(excelVOSMap.get(key), true);
//            }
//            index++;
//        }
//        try {
//            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//            ServletOutputStream out = response.getOutputStream();
//            writer.flush(out, true);
//            writer.close();
//            IoUtil.close(out);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    /**
     * 异常 error 返回
     *
     * @param error 错误信息数据
     */
    public static void exportError(HttpServletResponse response, Object error) {
        // 设置response的Content-Type为application/json
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        // 将JSON字符串写入response的输出流
        try {
            String respJson = JSON.toJSONString(error);
            response.getWriter().write(respJson);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

